<template>
  <el-dialog :title="titleMap[mode]" v-model="visible" :width="1500" destroy-on-close :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" @closed="$emit('closed')" align-center>
    <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="100" ref="dialogForm">
        <el-row :gutter="1">
            <el-col :span="8">
                <el-form-item label="报废单号" prop="return_code">
                    <el-input v-model="form.return_code" placeholder="请输入报废单号" clearable></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="报废日期" prop="open_date">
                    <el-date-picker v-model="form.open_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="仓库" prop="ware_id">
                    <el-select v-model="ware_id" filterable style="width: 100%" placeholder="仓库" @change="wareChange" clearable>
                    <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id"/>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-col :span="24">
            <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" clearable></el-input>
            </el-form-item>
        </el-col>
        <el-form-item label="报废清单" prop="detail">
            <div class="flex">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="checkProduct" v-if="mode!='turn'">选择商品</el-button>
                <el-form-item label="扫码录入">
                    <div style="display:flex;width:100%">
                        <el-input v-model="bar_code" ref="barInput" v-if="barInput == 0" @input="handInput"></el-input>
                        <el-switch v-model="barInput" :active-value="0" :inactive-value="1" @change="barChange"></el-switch>
                    </div>
                </el-form-item>
            </div>
            <sc-form-table ref="table" v-model="form.detail" :addTemplate="addTemplate" placeholder="暂无数据" height="400" hideAdd show-summary>
                <el-table-column label="商品名称" align="center">
                    <template #default="scope">
                    {{ scope.row.goods_name }}
                    </template>
                </el-table-column>
                <el-table-column label="商品编号" align="center">
                    <template #default="scope">
                    {{ scope.row.goods_code }}
                    </template>
                </el-table-column>
				<el-table-column label="商品图片" align="center">
					<template #default="scope">
						<el-image v-if="scope.row.goods_image" style="width: 30px; height: 30px; border-radius: 5px;" :src="scope.row.goods_image" :preview-src-list="[scope.row.goods_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
					</template>
				</el-table-column>
                <el-table-column label="商品单位" align="center" prop="unit_name"></el-table-column>
                <el-table-column label="数量" prop="number" align="center">
                    <template #default="scope">
                    <el-input v-model="scope.row.number" placeholder="数量" @focus="onFocus($event)"></el-input>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="单价" prop="price" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.price" placeholder="单价" @input="totalCompute" @focus="onFocus($event)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="小计" prop="total_price" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.total_price" placeholder="小计" readonly></el-input>
                    </template>
                </el-table-column> -->
                <el-table-column label="仓库" align="center">
                    <template #default="scope">
                    <el-select v-model="scope.row.ware_id" filterable style="width: 100%" placeholder="仓库">
                        <!--  @change="getLocationList(scope.row)" -->
                        <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id"/>
                    </el-select>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="库位" align="center">
                    <template #default="scope">
                        <el-select v-model="scope.row.location_id" filterable style="width: 100%" placeholder="库位" >
                            <el-option v-for="item in scope.row.locationList" :key="item.id" :label="item.position_name" :value="item.id" />
                        </el-select>
                    </template>
                </el-table-column> -->
                <el-table-column label="备注" prop="remark" align="center">
                    <template #default="scope">
                    <el-input v-model="scope.row.remark" placeholder="备注"></el-input>
                    </template>
                </el-table-column>
            </sc-form-table>
        </el-form-item>
        <el-form-item label="附件" prop="enclosure">
            <sc-upload-file v-model="form.enclosure" :is_same_name="1">
            <el-button type="primary" icon="el-icon-upload">选择文件</el-button>
            </sc-upload-file>
        </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible=false">取 消</el-button>
      <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>
  <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0}"></select-goods>
</template>

<script>
import selectGoods from '@/views/goods/info/selectGoods.vue';

export default {
    components: {selectGoods},
    emits: ['success', 'closed'],
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增',
                edit: '编辑',
                show: '查看',
            },
            visible: false,
            isSaveing: false,
            form: {
                id: "",
                return_code: "",
                open_date: this.moment().format('YYYY-MM-DD'),
                remark: "",
                enclosure: "",
                detail: [],
            },
            addTemplate: {},
            dialog: {
                goods: false,
            },
            wareList: [],
            ware_id: "",
            rules: {
                return_code: [
                {required: true, message: '请输入报废单号'}
                ],
                open_date: [
                {required: true, message: '请选择报废日期'}
                ],
                detail: [
                {required: true, message: '请选择报废商品'}
                ],
            },
            barInput: 1,
            bar_code: "",
        }
    },
    created() {
        this.handInput = this.debounce(this.handInput, 500);
    },
    mounted() {
        this.getWare()
        this.getGetCode()
    },
    methods: {
        // 防抖
        debounce(func, delay){
            let timeoutId;
            return function(...args) {
                if (timeoutId) {
                    clearTimeout(timeoutId);
                }
                timeoutId = setTimeout(() => {
                    func.apply(this, args);
                }, delay);
            };
        },
        handInput(e){
            this.getProduct(e)
        },
        async getProduct(e){
            var res = await this.$API.goods.goods.search.get({ bar_code:e });
            let exist = this.common.isExist(res.data.id, this.form.detail, 'goods_id')
            if (exist) {
                this.form.detail.map(item1=>{
                    if(item1.goods_id == res.data.id){
                        item1.number += 1
                    }
                })
            }else{
                let array = []
                array.push({
                    goods_id: res.data.id,
                    goods_name: res.data.goods_name,
                    unit_name: res.data.unit && res.data.unit.unit_name,
                    mater_code: res.data.material_code,
                    goods_code: res.data.goods_code,
                    goods_image: res.data.goods_image,
                    number: 1,
                    location_id: "",
                    ware_id: this.ware_id ? this.ware_id : '',
                })
			    this.form.detail = [...this.form.detail, ...array]
            }
            this.bar_code = ""
        },
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                this.isSaveing = true;
                let flag = false
                this.form.detail.map(item => {
                    if (!item.number || !item.ware_id) {
                    flag = true
                    }
                })
                if (flag) {
                    this.isSaveing = false
                    this.$message.error("报废商品数量/仓库不能为空!")
                    return
                }
                var res = [];
                if (this.form.id) {
                    res = await this.$API.procure.customreturn.edit.post(this.form);
                } else {
                    res = await this.$API.procure.customreturn.add.post(this.form);
                }
                this.isSaveing = false;
                if (res.code == 1) {
                    this.$emit('success', this.form, this.mode)
                    this.visible = false;
                    this.$message.success("操作成功")
                } else {
                    this.$alert(res.message, "提示", {type: 'error'})
                }
                }
            })
        },
        //表单注入数据
        async setData(data) {
            this.form.id = data.id
            var res = await this.$API.procure.customreturn.detail.get({id: data.id});
            this.form.return_code = res.data.return_code
            this.form.remark = res.data.remark
            this.form.enclosure = res.data.enclosure
            let array = []
            res.data.detail.map(item => {
                array.push({
                id: item.id,
                goods_id: item.goods_id,
                goods_name: item.goods && item.goods.goods_name,
					goods_image: item.goods && item.goods.goods_image,
                unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
                goods_code: item.goods && item.goods.goods_code,
                number: item.number,
                price: item.price,
                total_price: item.total_price,
                remark: item.remark,
                ware_id: item.ware_id,
                location_id: item.location_id,
                })
            })
            this.form.detail = array
        },
        // 选择商品
        checkProduct() {
            this.dialog.goods = true
            this.$nextTick(() => {
                this.$refs.goodsDialog.open('add')
            })
        },
        // 选择商品返回
        goodsUpdate(data) {
            let array = []
            data.map((item) => {
                array.push({
                goods_id: item.id,
                goods_name: item.goods_name,
					goods_image: item.goods_image,
                unit_name: item.unit && item.unit.unit_name,
                mater_code: item.material_code,
                goods_code: item.goods_code,
                location_id: "",
                ware_id: this.ware_id ? this.ware_id : '',
                })
            })
            let existingIds = this.form.detail.map(item => item.goods_id);
            for (let i = array.length - 1; i >= 0; i--) {
                if (existingIds.includes(array[i].goods_id)) {
                array.splice(i, 1);
                }
            }
            this.form.detail = [...this.form.detail, ...array]
        },
        /**获取报废单号*/
        async getGetCode() {
            var res = await this.$API.procure.customreturn.code.get();
            this.form.return_code = res.data.code
        },
        /**获取仓库*/
        async getWare() {
            var res = await this.$API.goods.ware.all.get();
            this.wareList = res.data;
            if (this.mode == 'add') {
                res.data.map(item => {
                if (item.is_default == 1) {
                    this.ware_id = item.id
                }
                })
            }
        },
        async getLocationList(row) {
            const res = await this.$API.goods.ware.position.post({ware_id: row.ware_id})
            row.locationList = res.data
        },
        onFocus(event) {
            event.target.select();
        },
        totalCompute() {
            this.form.detail.map(item => {
                if (item.price && item.number) {
                item.total_price = (Number(item.number) * Number(item.price)).toFixed(2)
                }
            })
        },
        wareChange(e) {
            this.form.detail.map(item => item.ware_id = e)
        },
        barChange(e){
            if(e == 0){
                this.$nextTick(()=>{
                    this.$refs.barInput.focus()
                })
            }
        },
    }
}
</script>

<style>
.flex{
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding-right: 35px;
}
</style>
